import logging
import pymysql
from xpinyin import Pinyin
from django.http import JsonResponse, HttpResponse
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *
from django.db import connection

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def all_friend(params):
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    pin = Pinyin()
    result = mysql_tools.select_all(UserSqlMap.all_friend.format(**params))
    if not result:
        return success_response({})
    if isinstance(result,JsonResponse):
        return result
    result = sorted(result, key=lambda x: pin.get_pinyin(x["real_name"]))
    result_dict = {}
    for res in result:
        if res["img_path"]:
            res["img_path"] = "static/image/" + res["img_path"]
        pinyin_name = pin.get_pinyin(res["real_name"])
        result_dict[pinyin_name.capitalize()[0]] = []
    for res in result:
        result_dict[pin.get_pinyin(res["real_name"]).capitalize()[0]].append(res)
    return success_response(result_dict)




def check_friend(params):
    dict = {
        "user_id": "contact_id",
        "user": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    result = mysql_tools.select_one(UserSqlMap.check_friend.format(**params))
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "all_friend": all_friend,
        "check_friend": check_friend,
    })
